<template>
  <div id="wallet">
    <top-bar :title="title"></top-bar>
    <div class="recharge">
      <div class="banner" v-if="bannerUrl">
        <img :src="bannerUrl" alt />
      </div>
      <div class="banner" v-else>
        <img src="@/assets/imgs/wallet_hd.png" />
      </div>
      <ul class="denomination">
        <li v-for="(detail,index) in rechargeList" @click="chooseTab(index)" :key="index" :class="{active : detail.show == true}">
          &yen;{{detail.chargeAmt}}
          <span v-show="Number(detail.show) && detail.backMoney != 0"></span>
        </li>
      </ul>
      <div class="other">
        <input type="tel" v-model="inpValue" placeholder="其他金额" style="text-align:center;" @focus="clearChoose()" maxlength="12" />
        <div ref="user" class="other_text" v-show="this.give >= 0">
          充值 {{recharge}}
          <b v-show="this.give > 0">赠送 {{give}}</b>
          到账 {{total}}
        </div>
      </div>
      <div class="payChoose">
        <md-selector
          v-model="isSelectorShow"
          :data="data[0]"
          :default-index="0"
          title="余额充值"
          okText="确认"
          cancelText="取消"
          @confirm="onSelectorConfirm($event)"
          is-check
        ></md-selector>
      </div>
      <div class="contain_recharge">
        <div class="agreement">
          <p>
            点击充值，即表示您已经阅读并同意
            <span @click="rechargeAgt">《用户充值协议》</span>
          </p>
        </div>
        <div class="rzBtn" @click="rechargeBtn">充值</div>
      </div>
    </div>
    <md-dialog title="确认" :closable="false" v-model="actDialog.open" :btns="actDialog.btns">请确认充值是否已经完成</md-dialog>
  </div>
</template>
<script>
import { Tabs, Icon, Field, InputItem, Toast, Selector, Dialog } from 'mand-mobile';
import TopBar from '@/components/TopBar';
import Loading from '@/components/loading';
import Utils from '@/common/pakjUtils';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import http from '@/common/http';
export default {
  components: {
    [Tabs.name]: Tabs,
    [Icon.name]: Icon,
    [TopBar.name]: TopBar,
    [Field.name]: Field,
    [Toast.name]: Toast,
    [Dialog.name]: Dialog,
    [InputItem.name]: InputItem,
    [Selector.name]: Selector
  },
  data() {
    return {
      title: '充值',
      rechargeList: [],
      value: '',
      recharge: '',
      give: '',
      total: '',
      inpValue: '',
      bannerUrl: '',
      rechargeId: '',
      tagOrInput: 'tag',
      isSelectorShow: false,
      order_no: '',
      disablePayButton: false, // 禁用支付
      data: '',
      actDialog: {
        open: false,
        btns: [
          {
            text: '重新充值',
            handler: this.onActCancel
          },
          {
            text: '已完成充值',
            handler: this.onActConfirm
          }
        ]
      }
    };
  },
  created() {
    let orderno = this.$route.query.orderno;
    if (orderno) {
      this.order_no = orderno;
    } else {
      let charge_no = localStorage.getItem('recharge_order_no');
      if (charge_no) {
        this.order_no = charge_no;
      }
    }
    let calledPay = localStorage.getItem('recharge_states');
    if (calledPay === '1') {
      this.actDialog.open = true;
    }
    if (Utils.isApp()) {
      // 在app
      this.data = [
        [
          {
            text: '<img src="' + require('@/assets/imgs/cz_wx_icon@2x.png') + '">微信支付',
            value: '1001'
          },
          {
            text: '<img src="' + require('@/assets/imgs/cz_zfb_icon@2x.png') + '">支付宝支付',
            value: '1002'
          }
        ]
      ];
    } else {
      if (Utils.isWeixinBroswer()) {
        // 微信中
        this.data = [
          [
            {
              text: '<img src="' + require('@/assets/imgs/cz_wx_icon@2x.png') + '">微信支付',
              value: '1001'
            }
          ]
        ];
      } else {
        // H5中
        this.data = [
          [
            {
              text: '<img src="' + require('@/assets/imgs/cz_wx_icon@2x.png') + '">微信支付',
              value: '1001'
            },
            {
              text: '<img src="' + require('@/assets/imgs/cz_zfb_icon@2x.png') + '">支付宝支付',
              value: '1002'
            }
          ]
        ];
      }
    }
  },
  mounted() {
    Loading.show();
    http.post('/recharge/getRechargeList').then(res => {
      Loading.hide();
      console.log(res.data);
      if (!res) {
        return false;
      }
      if (res.data.code === '000000') {
        let param = res.data.data;
        this.bannerUrl = param.bannerUrl;
        this.rechargeList = param.details;
        this.recharge = this.rechargeList[0].chargeAmt;
        this.give = this.rechargeList[0].backMoney;
        this.total = Number(this.recharge) + Number(this.give);
        this.value = this.rechargeList[0].chargeAmt;
        this.rechargeId = param.id;
      } else {
        Dialog.alert({
          title: '提示',
          content: res.data.msg,
          confirmText: '确定'
        });
      }
    });
  },
  methods: {
    ...mapActions(['WxWalltPayment', 'h5WxWalltPayment']),
    // 充值金额选项样式
    chooseTab(index) {
      this.tagOrInput = 'tag';
      this.inpValue = '';
      this.rechargeList.forEach((item, i) => {
        item.show = '0';
        if (i === index) {
          item.show = '1';
          this.value = item.chargeAmt;
          this.recharge = item.chargeAmt;
          this.give = item.backMoney;
          this.total = Number(this.recharge) + Number(this.give);
          this.$refs.user.style.display = 'block';
        }
      });
    },
    // 点击输入框清除充值标签
    clearChoose() {
      if (!this.inpValue) {
        this.value = '';
        this.$refs.user.style.display = 'none';
        this.rechargeList.forEach((item, i) => {
          item.show = '0';
        });
        this.tagOrInput = 'input';
      }
    },
    // 确认充值
    onSelectorConfirm(obj) {
      /* eslint-disable */
      var os = Utils.getOSName();
      if (!this.disablePayButton) {
        this.disablePayButton = true; // 支付禁用
        setTimeout(() => {
          this.disablePayButton = false;
        }, 2000);
        let Param = {
          order_no: this.order_no,
          payType: obj.value
        };
        console.log(Param);
        if (Utils.isApp()) {
          // 判断当前环境是否在app
          if ((os === 'Linux' || os === 'Android') && handler) {
            handler.payParam(JSON.stringify(Param));
          } else if ((os === 'iOS' || os === 'MacOSX') && window.webkit) {
            window.webkit.messageHandlers.payParam.postMessage(JSON.stringify(Param));
          }
          window.paySuccess = this.paySuccess;
        } else {
          if (Utils.isWeixinBroswer()) {
            // 使用微信公众号充值
            this.WxWalltPayment(Param)
              .then(() => {
                let params = this.getWalltPaymentInfo.JSPParam;
                wx.config({
                  debug: false,
                  appId: params['appId'],
                  timestamp: params['timestamp'],
                  nonceStr: params['noncestr'],
                  signature: params['signature'],
                  jsApiList: ['chooseWXPay']
                });
                wx.ready(() => {
                  wx.chooseWXPay({
                    timestamp: params['timestamp'],
                    nonceStr: params['noncestr'],
                    package: 'prepay_id=' + params['package'], // TODO May need remove 'prepay\_id='
                    signType: 'MD5', // TODO If this didn't work . Use 'SHA1'.
                    paySign: params['paySign'],
                    success: res => {
                      if (res.errMsg === 'chooseWXPay:ok') {
                        this.paySuccess();
                      }
                    },
                    fail: res => {
                      this.paySuccess();
                    }
                  });
                });
              })
              .catch(reason => {
                if (reason.message === '200008') {
                  this.paySuccess();
                } else {
                  Dialog.alert({
                    title: '错误',
                    content: '充值失败',
                    confirmText: '确定'
                  });
                }
              });
          } else {
            if (obj.value === '1001') {
              // 使用H5微信支付
              this.h5WxWalltPayment(Param)
                .then(() => {
                  localStorage.setItem('recharge_order_no', this.order_no);
                  localStorage.setItem('recharge_states', '1');
                  window.location.href = this.getH5WalltInfo.JSPParam.mweb_url;
                })
                .catch(reason => {
                  if (reason.message === '200008') {
                    this.paySuccess();
                  } else {
                    Dialog.alert({
                      title: '错误',
                      content: '充值失败',
                      confirmText: '确定'
                    });
                  }
                });
            } else if (obj.value === '1002') {
              // 使用支付宝支付
              this.h5WxWalltPayment(Param)
                .then(() => {
                  localStorage.setItem('recharge_order_no', this.order_no);
                  localStorage.setItem('recharge_states', '1');
                  let htmlStr = this.getH5WalltInfo.AlipayBody;
                  const div = document.createElement('div'); // 创建div
                  div.innerHTML = htmlStr; // 将返回的form 放入div
                  document.body.appendChild(div);
                  document.forms[0].submit();
                })
                .catch(reason => {
                  if (reason.message === '200008') {
                    this.paySuccess();
                  } else {
                    Dialog.alert({
                      title: '错误',
                      content: '充值失败',
                      confirmText: '确定'
                    });
                  }
                });
            }
          }
        }
      }
    },
    //app通信回调查询 和 H5充值查询
    paySuccess(msg) {
      let param = {
        id: this.order_no
      };
      Loading.show();
      http.post('/recharge/toQueryRecharge', param).then(res => {
        Loading.hide();
        if (!res) {
          return false;
        }
        if (res.data.code === '000000') {
          let dataP = res.data.data;
          localStorage.setItem('accountMoney', this.returnFloat(decryptByDESModeEBC(dataP.accountMoney)));
          localStorage.setItem('backMoney', this.returnFloat(decryptByDESModeEBC(dataP.backMoney)));
          localStorage.setItem('createDate', this.timestampToTime(dataP.createDate));
          localStorage.setItem('paymentType', dataP.paymentType);
          localStorage.setItem('userPhone', decryptByDESModeEBC(dataP.userPhone).replace(/^(.{3})(?:\d+)(.{4})$/, '$1****$2'));
          this.$router.push({
            name: 'MyWalletRechargeSuccess'
          });
        } else {
          Dialog.alert({
            title: '错误',
            content: '充值失败',
            confirmText: '确定'
          });
        }
      });
    },
    // 充值协议
    rechargeAgt() {
      this.$router.push({
        name: 'rechargeAgt'
      });
    },
    // 充值
    rechargeBtn() {
      if (!this.value && !this.inpValue) {
        Toast({
          content: '请选择或输入充值金额',
          duration: 3000,
          hasMask: true
        });
        return false;
      } else {
        let value = '';
        if (this.value) {
          value = this.value;
        } else if (this.inpValue) {
          value = this.inpValue;
        }
        let param = {
          rechargeId: this.rechargeId,
          chargeAmt: encryptByDESModeEBC(value)
        };
        Loading.show();
        http.post('/recharge/toRecharge', param).then(res => {
          Loading.hide();
          console.log(res.data);
          if (!res) {
            return false;
          }
          if (res.data.code === '000000') {
            this.order_no = res.data.data;
            this.isSelectorShow = true;
          } else {
            Dialog.alert({
              title: '提示',
              content: res.data.msg,
              confirmText: '确定'
            });
          }
        });
      }
    },
    // 时间戳转化为时间
    timestampToTime(timestamp) {
      var date = new Date(timestamp); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + '-';
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var D = date.getDate() + ' ';
      var h = date.getHours() + ':';
      var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      var s = date.getSeconds();
      return Y + M + D + h + m + s;
    },
    onActConfirm() {
      localStorage.removeItem('recharge_order_no');
      localStorage.removeItem('recharge_states');
      this.actDialog.open = false;
      this.paySuccess();
    },
    onActCancel() {
      localStorage.removeItem('recharge_order_no');
      localStorage.removeItem('recharge_states');
      this.actDialog.open = false;
    },
    returnFloat(value) {
      value = Math.round(parseFloat(value) * 100) / 100;
      let xsd = value.toString().split('.');
      if (xsd.length === 1) {
        value = value.toString() + '.00';
        return value;
      }
      if (xsd.length > 1) {
        if (xsd[1].length < 2) {
          value = value.toString() + '0';
        } else if (xsd[1].length > 2) {
          value = value.toFixed(2);
        }
        return value;
      }
    }
  },
  computed: {
    ...mapGetters(['getWalltPaymentInfo', 'getH5WalltInfo'])
  },
  // 监听input框里面的值，赋值给recharge
  watch: {
    inpValue: function(n, o) {
      if (this.inpValue.length === 1) {
        this.inpValue = this.inpValue.replace(/[^1-9]/g, '');
      } else {
        this.inpValue = this.inpValue.replace(/[^0-9]/g, '');
      }
      let param = {
        rechargeId: this.rechargeId,
        chargeAmt: encryptByDESModeEBC(this.inpValue)
      };
      if (this.inpValue && this.tagOrInput === 'input') {
        http.post('/recharge/calcBackMoney', param).then(res => {
          if (!res) {
            return false;
          }
          if (res.data.code === '000000') {
            this.give = res.data.data;
            this.total = Number(this.recharge) + Number(this.give);
            this.$refs.user.style.display = 'block';
          }
        });
      } else if (this.tagOrInput === 'tag') {
      } else {
        this.$refs.user.style.display = 'none';
      }
      if (this.tagOrInput === 'input') {
        this.recharge = this.inpValue;
      }
    }
  }
};
</script>
<style lang="stylus">
p {
  display: block;
  margin-block-start: 0px;
  margin-block-end: 0px;
  margin-inline-start: 0px;
  margin-inline-end: 0px;
}

.md-radio-content {
  font-size: 26px;
  color: #666;
}

.md-radio-content img {
  width: 44px;
  height: 44px;
  margin: 0px 15px;
  position: relative;
  top: 15px;
}

#wallet {
  height: 100vh;
  background-color: color-primary-background;
}

i {
  font-style: normal;
}

.banner img {
  width: 100%;
}

.denomination {
  background-color: #fff;
  color: #333;
  font-size: 30px;
  display: flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px 30px;
}

.denomination li {
  width: 216px;
  height: 80px;
  line-height: 80px;
  text-align: center;
  border: solid 2px #e0e0e0;
  position: relative;
  border-radius: 6px;
  margin-top: 10px;
  margin-bottom: 10px;
}

.denomination li span {
  position: absolute;
  width: 56px;
  height: 38px;
  background: url('../../assets/imgs/cz_fanquan@2x.png') no-repeat center;
  background-size: 100% 100%;
  bottom: 0;
  right: 0;
}

.denomination li.active {
  border: solid 1px #ff6917;
}

.other {
  background-color: #fff;
  height: 150px;
  padding: 0px 30px;
}

.other input {
  font-size: 30px;
  color: #333;
  outline: none;
  border: solid 1px #e0e0e0;
  border-radius: 5px;
  background-color: #F6F6F6;
  -webkit-appearance: none;
  height: 80px;
  line-height: 80px;
  width: 100%;
}

.other_text {
  font-size: 28px;
  color: #666;
  margin-top: 15px;
}

.contain_recharge {
  width: 100%;
  padding-bottom: 30px;
}

.agreement p {
  font-size: 22px;
  color: #999;
  margin: 20px 30px;
}

.agreement p span {
  color: #FF6917;
}

.rzBtn {
  height: 98px;
  line-height: 98px;
  font-size: 36px;
  text-align: center;
  background-color: #FF6917;
  color: #fff;
  border-radius: 7px;
  margin: 0px 30px;
}
</style>
